package org.groupg.practice.csv;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.time.LocalDate;

/**
 * 使用 commons-csv 功能进行读写 csv文件
 * <br><a href="https://commons.apache.org/proper/commons-csv/user-guide.html">用户手册</a>
 */
public class ReadAndWritePractice {
    static String filepath = "build/outFile/practice.CSV";
    public static void main(String[] args) {
        /**
         * 写文件
         */
        try (CSVPrinter printer = new CSVPrinter(new FileWriter(filepath), CSVFormat.EXCEL)) {
            printer.printRecord("id", "userName", "firstName", "lastName", "birthday");
            printer.printRecord(1, "john73", "John", "Doe", LocalDate.of(1973, 9, 15));
//            printer.println();
            printer.printRecord(2, "mary", "Mary", "Meyer", LocalDate.of(1985, 3, 29));
        } catch (IOException ex) {
            ex.printStackTrace();
        }



        try {
            Reader in = new FileReader(filepath);
            Iterable<CSVRecord> records = null;
            records = CSVFormat.EXCEL.parse(in);
            for (CSVRecord record : records) {
                String lastName = record.get("Last Name");
                String firstName = record.get("First Name");
                System.out.printf("lastName:%s,firstName:%s%n",lastName,firstName);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }
}
